<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElButton, ElCard, ElCheckbox, ElForm, ElFormItem, ElInput, ElMessage, ElTooltip } from 'element-plus';
import { userLoginApi } from '@/apis/api-user';
import { delLocal, getLocal, setLocal } from '@/common/common-helper';
import ReImageVerify from '@/components/ReImageVerify';
import SvgIconIndex from '@/components/SvgIconIndex.vue';
import { useSystemStore, useUserStore } from '@/stores';
import { USER_KEY_TOKEN_REMEMBER, setToken } from '@/utils/auth';

const router = useRouter();
const userStore = useUserStore();
const systemStore = useSystemStore();

const loginFormRef = ref(); // 登录表单ref
const isCapslock = ref(false); // 是否大写锁定
const imgCode = ref('');
const loading = ref(false); // 按钮loading
const verifyRef = ref(null);
const remember_password = ref(false);

const loginData = ref({
  username: '',
  password: '',
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入用户名',
      },
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入密码',
      },
      {
        min: 6,
        message: '密码不能少于6位',
        trigger: 'blur',
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入验证码',
      },
    ],
  };
});

onMounted(() => {
  if (getLocal(USER_KEY_TOKEN_REMEMBER) == null) {
    remember_password.value = false;
    loginData.value.username = '';
    loginData.value.password = '';
  } else {
    remember_password.value = true;

    const userVal = getLocal(USER_KEY_TOKEN_REMEMBER);

    loginData.value.username = userVal.u;
    loginData.value.password = userVal.p;
  }
});

/** 检查输入大小写 */
const checkCapslock = (event) => {
  // 防止浏览器密码自动填充时报错
  if (event) {
    isCapslock.value = event.getModifierState('CapsLock');
  }
};

// 记住密码
const onChangeRemember = (e) => {
  remember_password.value = e;

  if (!e) {
    delLocal(USER_KEY_TOKEN_REMEMBER);
  }
};

// 判断是否记住密码
const determineRememberPass = (password) => {
  if (remember_password.value) {
    setLocal(USER_KEY_TOKEN_REMEMBER, password);
  } else {
    delLocal(USER_KEY_TOKEN_REMEMBER);
  }
};

const handleLogin = () => {
  loginFormRef.value?.validate(async (valid) => {
    if (valid) {
      loading.value = true;

      if (loginData.value.captchaCode !== imgCode.value) {
        ElMessage.warning('验证码不正确');
        loading.value = false;
        loginData.value.captchaCode = '';
        verifyRef.value.getImgCode();

        return;
      }

      determineRememberPass({
        p: loginData.value.password,
        u: loginData.value.username,
      });

      const [err, data] = await userLoginApi({
        username: loginData.value.username,
        password: loginData.value.password,
      });

      if (!err) {
        const { accessToken } = data.data;

        setToken(accessToken, true);
        router.replace('/launch');

        systemStore.getSystemPermissionAllApi();
        systemStore.getSystemDeptAllApi();
        systemStore.getSystemRoleAllApi();
        setTimeout(() => {
          userStore.SELECT_LOGIN_CURRENT();
        });
      } else {
        loginData.value.captchaCode = '';
        verifyRef.value.getImgCode();
        loading.value = false;
      }
    }

    loading.value = false;
  });
};
</script>
<template>
  <div class="login-container">
    <!-- 登录表单 -->
    <ElCard class="w-100 !rounded-4 !border-none !bg-transparent">
      <div class="relative text-center">
        <h2>登录界面</h2>
      </div>

      <ElForm ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
        <!-- 用户名 -->
        <ElFormItem prop="username">
          <div class="w-full flex-y-center">
            <SvgIconIndex icon-class="user" class="mx-2" />
            <ElInput
              ref="username"
              v-model.trim="loginData.username"
              placeholder="请输入用户名"
              name="username"
              size="large"
              class="h-[48px]"
            />
          </div>
        </ElFormItem>

        <!-- 密码 -->
        <ElTooltip :visible="isCapslock" :content="'大写锁定已打开'" placement="right">
          <ElFormItem prop="password">
            <div class="w-full flex-y-center">
              <SvgIconIndex icon-class="lock" class="mx-2" />
              <ElInput
                v-model.trim="loginData.password"
                placeholder="请输入密码"
                type="password"
                name="password"
                size="large"
                class="h-[48px] pr-2"
                show-password
                @keyup="checkCapslock"
                @keyup.enter="handleLogin"
              />
            </div>
          </ElFormItem>
        </ElTooltip>

        <!-- 验证码 -->
        <ElFormItem prop="captchaCode">
          <div class="w-full flex-y-center">
            <SvgIconIndex icon-class="captcha" class="mx-2" />
            <ElInput
              v-model.trim="loginData.captchaCode"
              auto-complete="off"
              size="large"
              class="flex-1"
              placeholder="请输入验证码"
              maxlength="4"
              @keyup.enter="handleLogin"
            >
              <template #append>
                <ReImageVerify ref="verifyRef" v-model:code="imgCode" />
              </template>
            </ElInput>
          </div>
        </ElFormItem>
        <!-- 记住密码 -->
        <div class="remember">
          <ElCheckbox v-model="remember_password" label="记住密码" size="large" @change="(e) => onChangeRemember(e)" />
        </div>

        <!-- 登录按钮 -->
        <ElButton :loading="loading" type="primary" size="large" class="w-full" @click.prevent="handleLogin"
          >登录
        </ElButton>

        <!-- 账号密码提示 -->
        <div class="mt-10 text-sm">
          <span>账号: admin</span>
          <span class="ml-4"> 密码: Suntoon@123</span>
        </div>
      </ElForm>
    </ElCard>
  </div>
</template>
<style scoped lang="scss">
:deep(.el-input-group__append) {
  padding: 0 !important;
}

.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background: url('../../assets/images/login-bg.jpg') no-repeat center right;
  .login-form {
    padding: 30px 10px;
  }

  .remember {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;

    :deep(.el-checkbox__label) {
      font-size: 16px;
    }
    :deep(.el-checkbox__inner) {
      width: 18px;
      height: 18px;
    }
    :deep(.el-checkbox__inner::after) {
      top: 3px;
      left: 6px;
    }
  }
}

:deep(.el-form-item) {
  background: $input-background;
  border: 1px solid $border-color;
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}
</style>
